package com.ellecity06.common.base

import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.view.LoadUiIntent
import com.ellecity06.common.helper.PagerHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2023/4/6 14:41
 * @des
 */
open class BaseViewModel : ViewModel(), LifecycleObserver {
    open val pagerHelper: PagerHelper by lazy { PagerHelper() }
    // loading 页面状态
    private val _loadUiIntentFlow: Channel<LoadUiIntent> = Channel()
    val loadUiIntentFlow: Flow<LoadUiIntent> = _loadUiIntentFlow.receiveAsFlow()
     fun showToast(message: String?) {
        sendLoadUiIntent(LoadUiIntent.Error(message?:"未知错误"))
    }

     fun showLoading(text: String="加载中...") {
        sendLoadUiIntent(LoadUiIntent.Loading(text =text, true))
    }

     fun dismissLoading() {
        sendLoadUiIntent(LoadUiIntent.Loading(text = "", false))
    }

     fun tokenExpired(message: String) {
        sendLoadUiIntent(LoadUiIntent.AuthorizationExpired(message))
    }

    /**
     * 发送当前加载状态：Loading、Error、Normal
     */
     fun sendLoadUiIntent(loadUiIntent: LoadUiIntent) {
        viewModelScope.launch {
            _loadUiIntentFlow.send(loadUiIntent)
        }
    }
}